import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';

import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import {
  ellipsis,
  afterCloseModal,
  DescriptionItem,
  renderSignalIntensity,
  renderMeterStatus,
  download, formateObjToParamStr
} from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './../Pressure_sensors/Detail';
import './../Home/openlayers.less';
import ReactDataGrid from 'react-data-grid';
import config from "@/config/config";
import request from "@/utils/request";

const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;

@connect(({ hydrant_inspection_records, loading, global }) => ({
  hydrant_inspection_records,
  global,
  loading: loading.models.hydrant_inspection_records,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showdelBtn: find(this.permissions, { name: 'hydrant_delete' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      sortState: { sortColumn: null, sortDirection: null }
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      hydrant_inspection_records: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        hydrant_inspection_records: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'hydrant_inspection_records/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'hydrant_inspection_records/changeLoaded',
          });
          dispatch({
            type: 'hydrant_inspection_records/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'hydrant_inspection_records/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'hydrant_inspection_records/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  getConfigFunc = (cb) => {
    this.findChildConfig = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'hydrant_inspection_records/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      hydrant_inspection_records: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label="消防栓编号">
          {getFieldDecorator('hydrant_number', {
            initialValue: searchParams.hydrant_number,
          })(<Input style={{ width: '100px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="资产编号">
          {getFieldDecorator('hydrant_name', {
            initialValue: searchParams.hydrant_name,
          })(<Input style={{ width: '100px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="用户编号">
          {getFieldDecorator('hydrant_user_number', {
            initialValue: searchParams.hydrant_user_number,
          })(<Input style={{ width: '100px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  order_direction: searchParams.order_direction,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
         {/*  <Button
            style={{marginLeft:'8px'}}
            className={'btn-green'}
            type="primary"
            icon="export"
            onClick={this.handleExport}
          >导出日志
          </Button> */}
        </FormItem>

      </Form>
    );
  }
  handleExport=()=>{
    const {
      hydrant_inspection_records: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/hydrant_log_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&&${formateObjToParamStr(searchParams)}`)

  }
  keyPress = (e) => {
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press');
      const {
        hydrant_inspection_records: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
          start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
          end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
        });

      });
    }
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      hydrant_name:'',
      hydrant_number:'',
      imei:'',
      hydrant_user_number:'',
      address:'',
      online_status:'',
      page: 1,
      per_page: 50,
      order_direction:'desc',
      start_date:moment(new Date()).format('YYYY-MM-DD'),
      end_date:moment(new Date()).format('YYYY-MM-DD'),
    });
  };


  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    request(`/verify_password`, {
      method: 'post',
      data: {
        password: this.state.password,
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        if(response.data.data.verify===1){
          console.log('验证成功')
          dispatch({
            type: `hydrant_inspection_records/remove`,
            payload: { id },
            callback: () => {
              message.success('删除巡检记录成功');
              const {
                hydrant_inspection_records: { searchParams },
              } = that.props;
              that.handleSearch(searchParams);
            },
          });
        }else{
          message.error('密码验证失败,请重新操作')
        }


      }
      that.setState({password:''})

    });

  };



  render() {
    const that = this;
    let {
      hydrant_inspection_records: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW ,compare_data},
    } = this.props;

    const defaultColumnProperties = {

      resizable: true,
    };
    let type=searchParams.order_direction==='desc'?"swap":"swap"
    console.log('type',type)
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            hydrant_inspection_records: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name:  '消防栓编号',
        width: 100,
        frozen:true,
        key: 'number',
        formatter: (event) => {
          return <span style={{color:'blue',cursor:'pointer'}} onClick={(e) => {
            this.setState({
              editRecord: event.row.hydrant,
              infoModal: true,
            });
          }
          }>{event.row.hydrant.number}</span>;
        },
      },
      {
        name: <span>资产编号 </span> ,
        width: 100,
        key: 'name',
        frozen:true,
        formatter: (event) => {
          return event.row.hydrant.name
        },
      },
      {
        name: <span>用户编号 </span> ,
        width: 100,
        key: 'user_number',
        frozen:true,
        formatter: (event) => {
          return event.row.hydrant.user_number
        },
      },
      {
        name: '巡检时间',
        width: 170,
        key: 'created_at',
        frozen:true,
      },
      {
        name: '设备类型',
        key: 'type',
        width: 100,
        formatter: (event) => {
          return event.row.hydrant.type===1?'非取水栓':'取水栓'
        },
      },
      {
        name: '地址',
        key: 'address',
        width: 180,
        formatter: (event) => {
          return event.row.hydrant.address
        },
      },
      {
        name: '巡检累计流量(m³)',
        key: 'imei3w2',
        width: 150,
        formatter: (event) => {
          if(!event.row.parameters){
            return  ''
          }
          return <p style={{width:'100%',textAlign:'right'}}>{event.row.parameters.cumulative_flow}</p>;
        }
      },
      {
        name: '巡检瞬时流量(m³/h)',
        key: 'imeia2',
        width: 160,
        formatter: (event) => {
          if(!event.row.parameters){
            return  ''
          }
          return <p style={{width:'100%',textAlign:'right'}}>{event.row.parameters.instantaneous_flow}</p>;

        }
      },
      {
        name: '操作',
        width: 360,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row.hydrant,
                infoModal: true,
              });
            }
            }
          >设备详情
          </Button>
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="diff"
                onClick={(e) => {
                  const exit=find(compare_data,function (item,index){
                    return item.id===event.row.id
                  })
                  if(!exit){
                    compare_data.unshift({id:event.row.hydrant.id,name:event.row.hydrant.name,number:event.row.hydrant.number,address:event.row.hydrant.address})
                    console.log('compare_data0',compare_data)
                    this.props.dispatch({
                      type: 'global/changeOneProperty',
                      payload: {
                        compare_data:compare_data
                      },
                    });
                    message.success('加入对比成功')
                  }else{
                    message.error('该设备已经在对比列表')
                  }


                }
                }
              >加入对比
              </Button>
            </Fragment>
          {
            this.state.showdelBtn &&
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要删除"${event.row.created_at}"记录吗?`,
                  content: <div>
                    <div>请输入登陆密码 : <Input type={'password'} defaultValue={that.state.password}
                                          onChange={(e) => {
                                            e.persist()
                                            console.log(e)
                                            that.setState({password: e.target.value})
                                          }}></Input>
                    </div>
                    请谨慎操作！ </div>,
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除记录
            </Button>
          }
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>日志列表</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>巡检记录(条)</p>
            <h4>{meta.total}</h4>
          </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if (!String(row)) {
                  return;
                }
                this.props.dispatch({
                  type: 'hydrant_inspection_records/changeSelectRow',
                  payload: [row],
                });
              }
            }

            onGridSort={(sortColumn, sortDirection) => {
              const comparer = (a, b) => {
                if (sortDirection === 'ASC') {
                  return a[sortColumn] > b[sortColumn] ? 1 : -1;
                } else if (sortDirection === 'DESC') {
                  return a[sortColumn] < b[sortColumn] ? 1 : -1;
                }
              };
              console.log('sortDirection',sortDirection)
              console.log('sortColumn',sortColumn)
              const parseData=data.sort(comparer);
              console.log('parseData',parseData)
              this.props.dispatch({
                type: 'hydrant_inspection_records/sortData',
                payload: parseData,
              });
              // const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
            }}

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={800}
        visible={this.state.infoModal}
      >
        <Detail editRecord={this.state.editRecord}
                detailSaveCallback={()=>{
                  const {
                    hydrant_inspection_records: { searchParams },
                  } = that.props;
                  that.handleSearch(searchParams);
                }}
        ></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
